package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private HotelMapper hotelMapper;

    @Override
    public PageResult searchByparam(RequestParams params) throws IOException {
        SearchRequest searchRequest = new SearchRequest("hotel");

        basicQueryBuild(searchRequest,params);

        //排序
        if (StringUtils.isNotBlank(params.getLocation())){
            searchRequest.source().sort(
                    SortBuilders.geoDistanceSort("location", new GeoPoint(params.getLocation()))
                            .order(SortOrder.ASC).unit(DistanceUnit.KILOMETERS));
        }
        //分页
        searchRequest.source().from((params.getPage()-1)*params.getSize());
        searchRequest.source().size(params.getSize());
        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name");
        highlightBuilder.preTags("<em style='color:red'>");
        highlightBuilder.postTags("</em>");
        highlightBuilder.requireFieldMatch(false);
        searchRequest.source().highlighter(highlightBuilder);

        //发送请求,得到响应
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        //定义一个方法
        return matchAll(response);
    }


    @Override
    public Map<String, List<String>> filters(RequestParams params) throws IOException {

        HashMap<String, List<String>> map = new HashMap<>();
        SearchRequest searchRequest = new SearchRequest("hotel");
        basicQueryBuild(searchRequest,params);
        searchRequest.source().size(0);
        searchRequest.source().aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(200));
        searchRequest.source().aggregation(AggregationBuilders.terms("cityAgg").field("city").size(200));
        searchRequest.source().aggregation(AggregationBuilders.terms("starName").field("starName").size(200));

        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

        Aggregations aggregations = response.getAggregations();
        //brand 品牌
        ArrayList<String> brandList = new ArrayList<>();
        Terms brandAggregation = aggregations.get("brandAgg");
        List<? extends Terms.Bucket> buckets = brandAggregation.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            brandList.add(bucket.getKeyAsString());
        }
        map.put("brand",brandList);
        //city  城市
        ArrayList<String> cityList = new ArrayList<>();
        Terms cityAgg = aggregations.get("cityAgg");
        List<? extends Terms.Bucket> cityAggBuckets = cityAgg.getBuckets();
        for (Terms.Bucket cityAggBucket : cityAggBuckets) {
            cityList.add(cityAggBucket.getKeyAsString());
        }
        map.put("city",cityList);
        //starName 星级
        ArrayList<String> starNameList = new ArrayList<>();
        Terms starName = aggregations.get("starName");
        List<? extends Terms.Bucket> starNameBuckets = starName.getBuckets();
        for (Terms.Bucket starNameBucket : starNameBuckets) {
            starNameList.add(starNameBucket.getKeyAsString());
        }
        map.put("starName",starNameList);
        return map;
    }

    @Override
    public void saveOrUpdateEs(String hotel) throws IOException {
        Hotel hotel1 = JSON.parseObject(hotel, Hotel.class);
        HotelDoc hotelDoc = new HotelDoc(hotel1);

        IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());
        request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
        client.index(request,RequestOptions.DEFAULT);
    }

    @Override
    public void deleteEs(String id) throws IOException {
        DeleteRequest request = new DeleteRequest("hotel", id);
        client.delete(request,RequestOptions.DEFAULT);
    }

    @Override
    public List<String> getSuggestion(String prefix) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("hotel");
            // 2.准备DSL
            request.source().suggest(new SuggestBuilder().addSuggestion("suggestions",
                    SuggestBuilders.completionSuggestion("suggestion")
                            .prefix(prefix).skipDuplicates(true).size(10)));
            // 3.发起请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Suggest suggest = response.getSuggest();
            // 4.1.根据补全查询名称，获取补全结果
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            // 4.2.获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            // 4.3.遍历
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void basicQueryBuild(SearchRequest searchRequest, RequestParams params) {

        //复合查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //如果key为空
        if (StringUtils.isBlank(params.getKey())){
            //查询所有
            //searchRequest.source().query(QueryBuilders.matchAllQuery());
            boolQuery.must(QueryBuilders.matchAllQuery());
        }else {
            //匹配查询
            //searchRequest.source().query(QueryBuilders.matchQuery("all",params.getKey()));
            boolQuery.must(QueryBuilders.matchQuery("all",params.getKey()));
        }

        if (StringUtils.isNotBlank(params.getBrand())){
            boolQuery.filter(QueryBuilders.termQuery("brand",params.getBrand()));
        }
        if (StringUtils.isNotBlank(params.getCity())){
            boolQuery.filter(QueryBuilders.termQuery("city",params.getCity()));
        }
        if (StringUtils.isNotBlank(params.getStarName())){
            boolQuery.filter(QueryBuilders.termQuery("starName",params.getStarName()));
        }
        if (params.getMinPrice()!=null && params.getMaxPrice()!=null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(params.getMinPrice()).lte(params.getMaxPrice()));
        }

        //算分广告
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(boolQuery,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]
                        {new FunctionScoreQueryBuilder
                                .FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(10))});

        searchRequest.source().query(functionScoreQuery);
    }


    //解析响应结果
    private PageResult matchAll(SearchResponse response) {
        SearchHits responseHits = response.getHits();
        //总条数
        long total = responseHits.getTotalHits().value;
        System.out.println("查询到的总数:"+total);

        List<HotelDoc> list =new  ArrayList<>();
        SearchHit[] hits = responseHits.getHits();
        for (SearchHit hit : hits) {
            String source = hit.getSourceAsString();
            //解析响应结果
            //将读取到的source中的数据封装给HotelDoc
            HotelDoc hotelDoc = JSON.parseObject(source, HotelDoc.class);

            //高亮处理
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)){
                //获取高亮字段结果
                HighlightField highlightField = highlightFields.get("name");
                if (highlightField!=null){
                    Text[] fragments = highlightField.getFragments();
                    if (fragments!=null && fragments.length>0){
                        String nameHigligtField = fragments[0].toString();
                        hotelDoc.setName(nameHigligtField);
                    }
                }
                //设置距离
                Object[] sortValues = hit.getSortValues();
                if (sortValues!=null && sortValues.length>0){
                    hotelDoc.setDistance(sortValues[0]);
                }
            }
            list.add(hotelDoc);
        }
        return new PageResult(list,total);
    }
}
